pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs
import focusHost 1.0

Window {
    id: mainWindow
    width: 1200
    height: 800
    visible: true
    title: qsTr("调焦上位机 - Focus Host Control Interface")

    // Proper cleanup on window close
    onClosing: function (close) {
        if (serialController.isConnected) {
            serialController.closePort();
        }
    }

    // Backend controllers
    SerialPortController {
        id: serialController
        onErrorOccurred: function (error) {
            errorDialog.errorMessage = error;
            errorDialog.open();
        }
    }

    // Error dialog
    Dialog {
        id: errorDialog
        title: qsTr("错误")
        modal: true
        anchors.centerIn: parent

        property string errorMessage: ""

        contentItem: ColumnLayout {
            spacing: 10

            Label {
                text: errorDialog.errorMessage
                wrapMode: Text.Wrap
                Layout.preferredWidth: 300
            }

            Button {
                text: qsTr("确定")
                Layout.alignment: Qt.AlignRight
                onClicked: errorDialog.close()
            }
        }
    }

    // Main layout
    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 10
        spacing: 10

        // Top section: Port and Module selection
        RowLayout {
            Layout.fillWidth: true
            spacing: 10

            // Serial port selection panel
            GroupBox {
                id: portPanel
                title: qsTr("串口选择")
                Layout.preferredWidth: 400
                Layout.fillHeight: true

                ColumnLayout {
                    anchors.fill: parent
                    spacing: 10

                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 5

                        Label {
                            text: qsTr("端口:")
                        }

                        ComboBox {
                            id: portComboBox
                            Layout.fillWidth: true
                            model: serialController.availablePorts
                            onCurrentTextChanged: {
                                if (currentText !== "") {
                                    serialController.currentPort = currentText;
                                }
                            }
                            Component.onCompleted: {
                                // Restore saved port selection
                                var savedPort = serialController.currentPort;
                                if (savedPort !== "") {
                                    var index = find(savedPort);
                                    if (index >= 0) {
                                        currentIndex = index;
                                    }
                                }
                            }
                            Connections {
                                target: serialController
                                function onAvailablePortsChanged() {
                                    // Restore selection after refresh
                                    var savedPort = serialController.currentPort;
                                    if (savedPort !== "") {
                                        var index = portComboBox.find(savedPort);
                                        if (index >= 0) {
                                            portComboBox.currentIndex = index;
                                        }
                                    }
                                }
                            }
                        }

                        Button {
                            text: qsTr("刷新")
                            onClicked: serialController.refreshPorts()
                        }
                    }

                    // Serial port configuration
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 1
                        color: "lightgray"
                    }

                    Label {
                        text: qsTr("串口配置")
                        font.bold: true
                    }

                    GridLayout {
                        Layout.fillWidth: true
                        columns: 2
                        rowSpacing: 5
                        columnSpacing: 5

                        Label {
                            text: qsTr("波特率:")
                        }

                        ComboBox {
                            id: baudRateComboBox
                            Layout.fillWidth: true
                            enabled: !serialController.isConnected
                            model: [9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600]
                            currentIndex: model.indexOf(serialController.baudRate)
                            onActivated: {
                                serialController.baudRate = model[currentIndex];
                            }
                        }

                        Label {
                            text: qsTr("数据位:")
                        }

                        ComboBox {
                            id: dataBitsComboBox
                            Layout.fillWidth: true
                            enabled: !serialController.isConnected
                            model: [
                                {
                                    value: 5,
                                    text: "5"
                                },
                                {
                                    value: 6,
                                    text: "6"
                                },
                                {
                                    value: 7,
                                    text: "7"
                                },
                                {
                                    value: 8,
                                    text: "8"
                                }
                            ]
                            textRole: "text"
                            currentIndex: {
                                for (var i = 0; i < model.length; i++) {
                                    if (model[i].value === serialController.dataBits) {
                                        return i;
                                    }
                                }
                                return 3; // Default to 8
                            }
                            onActivated: {
                                serialController.dataBits = model[currentIndex].value;
                            }
                        }

                        Label {
                            text: qsTr("校验位:")
                        }

                        ComboBox {
                            id: parityComboBox
                            Layout.fillWidth: true
                            enabled: !serialController.isConnected
                            model: [
                                {
                                    value: 0,
                                    text: qsTr("无")
                                },
                                {
                                    value: 2,
                                    text: qsTr("偶")
                                },
                                {
                                    value: 3,
                                    text: qsTr("奇")
                                }
                            ]
                            textRole: "text"
                            currentIndex: {
                                for (var i = 0; i < model.length; i++) {
                                    if (model[i].value === serialController.parity) {
                                        return i;
                                    }
                                }
                                return 0; // Default to None
                            }
                            onActivated: {
                                serialController.parity = model[currentIndex].value;
                            }
                        }

                        Label {
                            text: qsTr("停止位:")
                        }

                        ComboBox {
                            id: stopBitsComboBox
                            Layout.fillWidth: true
                            enabled: !serialController.isConnected
                            model: [
                                {
                                    value: 1,
                                    text: "1"
                                },
                                {
                                    value: 2,
                                    text: "1.5"
                                },
                                {
                                    value: 3,
                                    text: "2"
                                }
                            ]
                            textRole: "text"
                            currentIndex: {
                                for (var i = 0; i < model.length; i++) {
                                    if (model[i].value === serialController.stopBits) {
                                        return i;
                                    }
                                }
                                return 0; // Default to 1
                            }
                            onActivated: {
                                serialController.stopBits = model[currentIndex].value;
                            }
                        }

                        Label {
                            text: qsTr("流控:")
                        }

                        ComboBox {
                            id: flowControlComboBox
                            Layout.fillWidth: true
                            enabled: !serialController.isConnected
                            model: [
                                {
                                    value: 0,
                                    text: qsTr("无")
                                },
                                {
                                    value: 1,
                                    text: qsTr("硬件")
                                },
                                {
                                    value: 2,
                                    text: qsTr("软件")
                                }
                            ]
                            textRole: "text"
                            currentIndex: {
                                for (var i = 0; i < model.length; i++) {
                                    if (model[i].value === serialController.flowControl) {
                                        return i;
                                    }
                                }
                                return 0; // Default to None
                            }
                            onActivated: {
                                serialController.flowControl = model[currentIndex].value;
                            }
                        }
                    }

                    // Connection control
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 1
                        color: "lightgray"
                    }

                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 5

                        Button {
                            id: connectButton
                            text: serialController.isConnected ? qsTr("断开") : qsTr("连接")
                            Layout.fillWidth: true
                            onClicked: {
                                if (serialController.isConnected) {
                                    serialController.closePort();
                                } else {
                                    serialController.openPort();
                                }
                            }
                        }

                        Rectangle {
                            id: statusIndicator
                            Layout.preferredWidth: 20
                            Layout.preferredHeight: 20
                            radius: 10
                            color: serialController.isConnected ? "green" : "red"
                            border.color: "black"
                            border.width: 1
                        }

                        Label {
                            text: serialController.isConnected ? qsTr("已连接") : qsTr("未连接")
                        }
                    }

                    Item {
                        Layout.fillHeight: true
                    }
                }
            }

            // Module ID selection panel
            GroupBox {
                id: modulePanel
                title: qsTr("模块选择")
                Layout.preferredWidth: 400
                Layout.fillHeight: true

                ColumnLayout {
                    anchors.fill: parent
                    spacing: 10

                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 5

                        Label {
                            text: qsTr("目标模块:")
                        }

                        ComboBox {
                            id: moduleComboBox
                            Layout.fillWidth: true

                            property var moduleModel: ListModel {
                                ListElement {
                                    moduleId: 0x02
                                    moduleName: "主激光准直调焦"
                                }
                                ListElement {
                                    moduleId: 0x03
                                    moduleName: "525准直调焦"
                                }
                                ListElement {
                                    moduleId: 0x07
                                    moduleName: "方位紧锁"
                                }
                                ListElement {
                                    moduleId: 0x08
                                    moduleName: "俯仰紧锁"
                                }
                                ListElement {
                                    moduleId: 0x0A
                                    moduleName: "粗跟踪罩"
                                }
                                ListElement {
                                    moduleId: 0x0C
                                    moduleName: "可见光相机光阑调节"
                                }
                                ListElement {
                                    moduleId: 0x0D
                                    moduleName: "可见光相机调焦"
                                }
                                ListElement {
                                    moduleId: 0x0E
                                    moduleName: "红外相机调焦"
                                }
                                ListElement {
                                    moduleId: 0x0F
                                    moduleName: "精跟调焦"
                                }
                                ListElement {
                                    moduleId: 0x10
                                    moduleName: "照明调焦"
                                }
                                ListElement {
                                    moduleId: 0x11
                                    moduleName: "滤光片切换1"
                                }
                                ListElement {
                                    moduleId: 0x12
                                    moduleName: "滤光片切换2"
                                }
                                ListElement {
                                    moduleId: 0x13
                                    moduleName: "发射开罩"
                                }
                                ListElement {
                                    moduleId: 0x15
                                    moduleName: "截至板切换"
                                }
                                ListElement {
                                    moduleId: 0x16
                                    moduleName: "精相机甲滤光轮切换"
                                }
                                ListElement {
                                    moduleId: 0x17
                                    moduleName: "精相机乙滤光轮切换"
                                }
                                ListElement {
                                    moduleId: 0x18
                                    moduleName: "发射调焦"
                                }
                            }

                            model: moduleModel
                            textRole: "moduleName"
                            onCurrentIndexChanged: {
                                if (currentIndex >= 0) {
                                    serialController.targetModuleId = moduleModel.get(currentIndex).moduleId;
                                }
                            }
                            Component.onCompleted: {
                                // Restore saved module ID selection
                                var savedModuleId = serialController.targetModuleId;
                                for (var i = 0; i < moduleModel.count; i++) {
                                    if (moduleModel.get(i).moduleId === savedModuleId) {
                                        currentIndex = i;
                                        return;
                                    }
                                }
                                // Default to first item if not found
                                currentIndex = 0;
                            }
                        }
                    }

                    Item {
                        Layout.fillHeight: true
                    }
                }
            }
        }

        // Middle section: Commands and Status
        RowLayout {
            Layout.fillWidth: true
            Layout.preferredHeight: 250
            spacing: 10

            // Command control panel
            GroupBox {
                id: commandPanel
                title: qsTr("控制命令")
                Layout.fillWidth: true
                Layout.fillHeight: true

                GridLayout {
                    anchors.fill: parent
                    columns: 2
                    rowSpacing: 10
                    columnSpacing: 10

                    // Query command
                    Label {
                        text: qsTr("查询状态:")
                        Layout.alignment: Qt.AlignRight
                    }

                    Button {
                        text: qsTr("查询")
                        enabled: serialController.isConnected
                        onClicked: serialController.sendQuery()
                        Layout.preferredWidth: 100
                    }

                    // Manual focus controls
                    Label {
                        text: qsTr("手动调焦:")
                        Layout.alignment: Qt.AlignRight
                    }

                    RowLayout {
                        spacing: 5

                        SpinBox {
                            id: stepLevelSpinBox
                            from: 1
                            to: 255
                            value: 10
                            editable: true
                        }

                        Button {
                            text: qsTr("调焦+")
                            enabled: serialController.isConnected
                            onClicked: serialController.sendManualFocusPlus(stepLevelSpinBox.value)
                        }

                        Button {
                            text: qsTr("调焦-")
                            enabled: serialController.isConnected
                            onClicked: serialController.sendManualFocusMinus(stepLevelSpinBox.value)
                        }
                    }

                    // Set focus value
                    Label {
                        text: qsTr("设定焦距值:")
                        Layout.alignment: Qt.AlignRight
                    }

                    RowLayout {
                        spacing: 5

                        SpinBox {
                            id: focusValueSpinBox
                            from: 0
                            to: 6000
                            value: 3000
                            editable: true
                        }

                        Button {
                            text: qsTr("发送")
                            enabled: serialController.isConnected
                            onClicked: serialController.sendSetFocusValue(focusValueSpinBox.value)
                        }
                    }

                    // Brake controls
                    Label {
                        text: qsTr("抱闸控制:")
                        Layout.alignment: Qt.AlignRight
                    }

                    RowLayout {
                        spacing: 5

                        Button {
                            text: qsTr("抱闸")
                            enabled: serialController.isConnected
                            onClicked: serialController.sendBrake()
                        }

                        Button {
                            text: qsTr("抱闸打开")
                            enabled: serialController.isConnected
                            onClicked: serialController.sendBrakeRelease()
                        }
                    }

                    // Auto focus
                    Label {
                        text: qsTr("自动调焦:")
                        Layout.alignment: Qt.AlignRight
                    }

                    RowLayout {
                        spacing: 5

                        SpinBox {
                            id: claritySpinBox
                            from: 0
                            to: 10000
                            value: serialController.imageClarity
                            editable: true

                            property real realValue: value / 100.0

                            textFromValue: function (value) {
                                return (value / 100.0).toFixed(2);
                            }

                            valueFromText: function (text) {
                                return Math.round(parseFloat(text) * 100);
                            }

                            onValueChanged: {
                                serialController.imageClarity = value;
                            }
                        }

                        Label {
                            text: qsTr("(清晰度: 0.00-100.00)")
                        }

                        Button {
                            text: qsTr("自动调焦")
                            enabled: serialController.isConnected
                            onClicked: serialController.sendAutoFocus(claritySpinBox.value)
                        }
                    }

                    // Reset
                    Label {
                        text: qsTr("系统控制:")
                        Layout.alignment: Qt.AlignRight
                    }

                    Button {
                        text: qsTr("复位")
                        enabled: serialController.isConnected
                        onClicked: serialController.sendReset()
                    }

                    Item {
                        Layout.fillHeight: true
                        Layout.columnSpan: 2
                    }
                }
            }

            // Status display panel
            GroupBox {
                id: statusPanel
                title: qsTr("状态显示")
                Layout.preferredWidth: 300
                Layout.fillHeight: true

                GridLayout {
                    anchors.fill: parent
                    columns: 2
                    rowSpacing: 10
                    columnSpacing: 10

                    // Work status section
                    Label {
                        text: qsTr("工作状态:")
                        font.bold: true
                        Layout.columnSpan: 2
                    }

                    Label {
                        text: qsTr("自检状态:")
                        Layout.alignment: Qt.AlignRight
                    }

                    Label {
                        text: serialController.selfCheckStatus
                        color: serialController.selfCheckStatus === "成功" ? "green" : "red"
                        font.bold: true
                    }

                    Label {
                        text: qsTr("调焦模式:")
                        Layout.alignment: Qt.AlignRight
                    }

                    Label {
                        text: serialController.focusMode
                        color: serialController.focusMode === "自动" ? "blue" : "black"
                        font.bold: true
                    }

                    Label {
                        text: qsTr("抱闸状态:")
                        Layout.alignment: Qt.AlignRight
                    }

                    Label {
                        text: serialController.brakeStatus
                        color: serialController.brakeStatus === "抱闸" ? "orange" : "green"
                        font.bold: true
                    }

                    // Separator
                    Rectangle {
                        Layout.columnSpan: 2
                        Layout.fillWidth: true
                        Layout.preferredHeight: 1
                        color: "lightgray"
                    }

                    // Position information
                    Label {
                        text: qsTr("位置信息:")
                        font.bold: true
                        Layout.columnSpan: 2
                    }

                    Label {
                        text: qsTr("当前焦距步数:")
                        Layout.alignment: Qt.AlignRight
                    }

                    Label {
                        text: serialController.currentFocusStep.toString()
                        font.pixelSize: 16
                        font.bold: true
                    }

                    Label {
                        text: qsTr("电机总行程:")
                        Layout.alignment: Qt.AlignRight
                    }

                    Label {
                        text: serialController.motorTotalTravel.toString()
                        font.pixelSize: 16
                        font.bold: true
                    }

                    Item {
                        Layout.fillHeight: true
                        Layout.columnSpan: 2
                    }
                }
            }
        }

        // Bottom section: Communication log
        GroupBox {
            id: logPanel
            title: qsTr("通信日志")
            Layout.fillWidth: true
            Layout.fillHeight: true
            Layout.minimumHeight: 250

            ColumnLayout {
                anchors.fill: parent
                spacing: 5

                // Log control buttons
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 5

                    Button {
                        text: qsTr("清空日志")
                        onClicked: serialController.logger.clear()
                    }

                    Button {
                        text: qsTr("保存日志")
                        onClicked: fileDialog.open()
                    }

                    Item {
                        Layout.fillWidth: true
                    }

                    Label {
                        text: qsTr("日志条数: ") + logListView.count
                    }
                }

                // Log list view
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    border.color: "lightgray"
                    border.width: 1

                    ListView {
                        id: logListView
                        anchors.fill: parent
                        anchors.margins: 2
                        clip: true
                        model: serialController.logger

                        ScrollBar.vertical: ScrollBar {
                            policy: ScrollBar.AlwaysOn
                        }

                        delegate: Item {
                            required property int index
                            required property string timestamp
                            required property string direction
                            required property string message

                            width: ListView.view.width - 20
                            height: logText.implicitHeight + 4

                            Rectangle {
                                anchors.fill: parent
                                color: parent.index % 2 === 0 ? "white" : "#f5f5f5"
                            }

                            Text {
                                id: logText
                                anchors.fill: parent
                                anchors.leftMargin: 5
                                anchors.rightMargin: 5
                                text: {
                                    var directionText = "";
                                    if (parent.direction === "TX") {
                                        directionText = "[发送]";
                                    } else if (parent.direction === "RX") {
                                        directionText = "[接收]";
                                    } else if (parent.direction === "INFO") {
                                        directionText = "[信息]";
                                    } else {
                                        directionText = "[错误]";
                                    }
                                    return parent.timestamp + " " + directionText + " " + parent.message;
                                }
                                font.family: "Courier New"
                                font.pixelSize: 11
                                wrapMode: Text.Wrap
                                color: {
                                    if (parent.direction === "TX")
                                        return "blue";
                                    if (parent.direction === "RX")
                                        return "green";
                                    if (parent.direction === "INFO")
                                        return "gray";
                                    return "red";
                                }
                            }
                        }

                        onCountChanged: {
                            // Auto-scroll to bottom when new items are added
                            Qt.callLater(function () {
                                logListView.positionViewAtEnd();
                            });
                        }
                    }
                }
            }
        }

        // File dialog for saving logs
        FileDialog {
            id: fileDialog
            title: qsTr("保存日志文件")
            fileMode: FileDialog.SaveFile
            nameFilters: [qsTr("文本文件 (*.txt)"), qsTr("所有文件 (*)")]
            defaultSuffix: "txt"
            onAccepted: {
                serialController.logger.saveToFile(selectedFile.toString().replace("file:///", ""));
            }
        }
    }
}
